﻿using HCQ2_Common;
using HCQ2_Common.Constant;
using HCQ2_Common.DD;
using HCQ2_Model;
using HCQ2_Model.DocModel;
using HCQ2_Model.ViewModel.WebAPI;
using HCQ2_Model.VLine.InputDto._0322;
using HCQ2_Model.VLine.InputDto._0607;
using HCQ2_Model.VLine.OutputDto;
using HCQ2_Model.VLine.OutputDto._06007;
using HCQ2_Model.VR.Model;
using HCQ2_Model.VR.Params;
using HCQ2WebAPI_Logic.BaseAPIController;
using HCQ2WebAPI_Logic.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace HCQ2WebAPI_Logic.DocumentController
{
    /// <summary>
    ///  合伙人控制器【2021-06-07】
    /// </summary>
    public class VRPartnerController:BaseWeiXinApiLogic
    {
        //****************************************************1.0 VR合伙人*******************************************************
        #region 1.0 给合伙人添加预付款 + WebApiResultJsonModel AddPrepayMoney(PartnerParam model)
        /// <summary>
        ///  给合伙人添加预付款
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel AddPrepayMoney(PartnerParam model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            if(model.folder_id<=0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "商铺id必传项！", null);
            List<T_User> u = null;
            //1.0 判断是否传递用户user_id
            if(model.user_id<=0 && (string.IsNullOrEmpty(model.login_name) || string.IsNullOrEmpty(model.user_phone)))
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "用户user_id和登录名、手机号不允许同时为空！", null);
            if (model.user_id > 0)
                u = operateContext.bllSession.T_User.Select(o => o.user_id == model.user_id);
            else
                u = operateContext.bllSession.T_User.Select(o => o.login_name.Equals(model.login_name) && o.user_phone.Equals(model.user_phone));
            //1.0 判断用户名、手机号是否对应用户
            if(u==null || u.Count!=1)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "用户不存在或登录名和手机号不匹配！", null);
            int user_id = HCQ2UI_Helper.Session.SysPermissSession.ChangeIdByGuid(model.userid);
            T_User operater = operateContext.bllSession.T_User.FindSingle(s => s.user_id == user_id);//操作人
            T_User user = u.FirstOrDefault();//申请人
            //2.0 判断用户是否为合伙人
            T_VRFounderApply m = operateContext.bllSession.T_VRFounderApply.FindSingle(s => s.apply_status == 1 && s.user_id == user.user_id && s.folder_id == model.folder_id);
            if(m==null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "用户还不是合伙人，不能添加预付款！", null);            
            //3.0 添加预付款
            decimal buy_gold = user.prepay_money, //变动前预付款
            _buy_gold = buy_gold + model.prepay_money;//变动后预付款
            int mark = operateContext.bllSession.T_User.Modify(new T_User { prepay_money = buy_gold+model.prepay_money }, s => s.user_id == user.user_id, "prepay_money");
            if (model.prepay_money > 0)
                operateContext.bllSession.T_VRGoldLog.Add(new T_VRGoldLog { user_id = user.user_id, user_name = user.user_name, unit_code = user.unit_code, gold_num = (_buy_gold - buy_gold), gold_type = 1, operator_type = 1, create_id = user.user_id, create_name = user.user_name, create_date = DateTime.Now, BeforBuyGold = buy_gold, BuyGold = _buy_gold, FolderId = model.folder_id });
            //判断充值者是否需要更新用户等级
            UserLevelColumn level = operateContext.bllSession.T_VRUserLevel.ResetUserLevel(user.user_id, model.folder_id, DateTime.Now.Year);
            operateContext.bllSession.T_User.Modify(new T_User { sell_money = level.saleNum, line_num = level.lineNum, user_level = level.userLevel }, s => s.user_id == operater.user_id, "sell_money", "line_num", "user_level");
            if (level.userLevel > m.user_level)
            {
                //等级发生变动写入：等级日志表
                operateContext.bllSession.T_VRUserLevelLog.Add(new T_VRUserLevelLog { user_id = user.user_id, folder_id = model.folder_id, user_name = user.user_name, user_level = level.userLevel, sell_money = level.saleNum, line_num = level.lineNum, create_id = operater.user_id, create_name = operater.user_name, create_date = DateTime.Now });
                //更新合伙人申请表用户等级
                operateContext.bllSession.T_VRFounderApply.Modify(new T_VRFounderApply { user_level = level.userLevel }, s => s.id == m.id, "user_level");
            }
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "添加预付款成功~", null);
        }
        #endregion

        #region 1.1 获取销售额列表 + WebApiResultJsonModel GetSaleList(SaleMoneyParam param)
        /// <summary>
        ///  获取销售额列表
        /// </summary>
        /// <param name="param">参数</param>
        /// <returns></returns>
        [HttpPost]
        [HCQ2_Common.Attributes.SkipApi]
        public WebApiResultJsonModel<List<SaleMoneyResult>> GetSaleList(SaleMoneyParam param)
        {
            if(string.IsNullOrEmpty(param.userid) && param.folder_id<=0)
                return ApiResultJsonModel<List<SaleMoneyResult>>.RedirectWebApi(WebResultCode.Exception, "用户userid、商铺id不能同时为空！", null);
           if(!string.IsNullOrEmpty(param.userid))
                param.user_id = HCQ2UI_Helper.Session.SysPermissSession.ChangeIdByGuid(param.userid);
            List<SaleMoneyResult> list = operateContext.bllSession.T_VRGoldLog.GetSaleList(param);
            return ApiResultJsonModel<List<SaleMoneyResult>>.RedirectWebApi(WebResultCode.Ok, "", list);
        }
        #endregion

        #region 1.2 提交合伙人申请 + WebApiResultJsonModel SubmitApply(FounderApply param)
        /// <summary>
        ///  提交合伙人申请
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel SubmitApply(FounderApply param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            if (param.folder_id <= 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "商铺id必传项！", null);
            var folder = operateContext.bllSession.T_DocumentFolder.FindSingle(s => s.folder_id == param.folder_id);
            if(folder==null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "商铺信息异常！", null);
            var refUser = operateContext.bllSession.T_User.FindSingle(s => s.user_id==param.ref_id);
            if(refUser==null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "推荐人信息异常！", null);
            var user = operateContext.bllSession.T_User.FindSingle(s => s.user_guid.Equals(param.userid));//HCQ2UI_Helper.Session.SysPermissSession.ChangeIdByGuid(param.userid);
            if(user.user_id <= 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "申请用户信息异常！", null);
            //判断申请人是否有同一个商铺的申请未过申请、或已过申请
            var apply = operateContext.bllSession.T_VRFounderApply.Select(s => s.user_id == user.user_id && s.folder_id == param.folder_id);
            if (apply != null && apply.Count>0)
            {
                int applyCount = apply.Where(o => o.apply_status == 0).Count();
                if (applyCount>0)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "已提交申请无需重复提交！", null);
                applyCount = apply.Where(o => o.apply_status == 1).Count();
                if (applyCount > 0)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "用户已经是当前商铺的合伙人无需重复提交！", null);
            }
            T_VRFounderApply obj = new T_VRFounderApply
            {
                user_id = user.user_id,
                ref_id = refUser.user_id,
                ref_name = refUser.user_name,
                apply_name = param.apply_name,
                apply_phone = param.apply_phone,
                folder_id = param.folder_id,
                folder_name = folder.folder_name,
                apply_date = DateTime.Now,
                apply_status = 0,
                user_level = 0
            };
            int mark = operateContext.bllSession.T_VRFounderApply.Add(obj);
            if (mark > 0)
            {
                //判断是否允许添加
                if(folder.founder_id<=0 || string.IsNullOrEmpty(folder.founder_name))
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "店铺创始人为空，消息推送失败！", null);
                //接收人
                var acceptUser = operateContext.bllSession.T_User.FindSingle(o => o.user_id == folder.founder_id);
                string phone = acceptUser?.user_phone;
                if(string.IsNullOrEmpty(phone))
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "店铺创始人手机号为空，消息推送失败！", null);
                //判断发送人是否有手机号
                if (string.IsNullOrEmpty(user.user_phone))
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "申请人手机号为空，不能推送消息！", null);
                string mess_note = $"有新的合伙申请等待审核";
                //0、同一个店铺、同一个发送人ID、同一个消息类别、同样的消息内容 只需要创建一条记录
                T_VRDDSendMess mess = operateContext.bllSession.T_VRDDSendMess.FindSingle(s => s.store_id == param.folder_id && s.send_id == user.user_id && s.mess_type.Equals("100") && s.mess_note.Equals(mess_note));
                //1、添加、更新【推送消息列表】
                if (mess != null)
                {
                    //更新               
                    mess.update_id = user.user_id;
                    mess.update_name = user.user_name;
                    mess.update_date = DateTime.Now;
                    mess.send_num = mess.send_num + 1;
                    if (mess.send_status == 1)
                        mess.send_status = 0;
                    else
                        mess.send_status = -1;
                    operateContext.bllSession.T_VRDDSendMess.Modify(mess, s => s.mess_id == mess.mess_id, "send_status", "update_id", "update_name", "update_date", "send_num");
                }
                else
                {
                    //添加
                    mess = new T_VRDDSendMess
                    {
                        send_id = user.user_id,
                        send_name = param.apply_name,
                        send_status = -1,
                        send_num = 1,
                        mess_type = "100",
                        store_id = param.folder_id,
                        store_name = folder.folder_name,
                        mess_note = mess_note,
                        create_id = user.user_id,
                        create_name = user.user_name,
                        create_date = DateTime.Now,
                        update_id = user.user_id,
                        update_name = user.user_name,
                        update_date = DateTime.Now
                    };
                    operateContext.bllSession.T_VRDDSendMess.Add(mess);
                }
                //2、写入推送用户列表
                var messUser = new T_VRDDSendUser
                {
                    mess_id = mess.mess_id,
                    create_id = user.user_id,
                    create_name = user.user_name,
                    create_date = DateTime.Now,
                    push_status = -1,
                    store_id = param.folder_id,
                    store_name = folder.folder_name,
                    accept_id = folder.founder_id,
                    accept_name = folder.founder_name,
                    accept_phone = phone,
                    accept_status = -1
                };
                operateContext.bllSession.T_VRDDSendUser.Add(messUser);
                //3、调用网易云信SDK，推送消息到度度圈App
                //店铺logo地址
                StringBuilder attach = new StringBuilder(); 
                string logo = !string.IsNullOrEmpty(folder.folder_url) ? folder.folder_url?.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"))) : "";
                attach.Append("{");
                attach.Append("\"logo\":\"" + logo + "\",");//店铺logo地址
                attach.Append("\"userid\":\"" + acceptUser.user_guid + "\",");//接收人用户编码
                attach.Append("\"storeName\":\"" + folder.folder_name + "\",");//店铺名
                attach.Append("\"messNote\":\""+ mess.mess_note + "\",");//消息内容
                attach.Append("\"messType\":\""+ mess.mess_type + "\",");//消息类别
                attach.Append("\"storeId\":\""+ mess.store_id + "\",");//店铺ID
                attach.Append("\"messUserId\":\""+ messUser.id + "\"");//推送用户列表主键值
                attach.Append("}");
                //string body = $@"消息内容：【{mess.mess_note}】、消息类别：【{mess.mess_type}】、店铺ID：【{mess.store_id}】、推送用户列表主键值：【{messUser.id}】";
                string imresult = IMUtil.ExecuteRequest(8, "from=" + user.user_phone + "&msgtype=0&to=" + phone + $"&attach={attach.ToString()}");
                IMResult json = JsonHelper.JsonStrToObject<IMResult>(imresult);
                if (json.code != 200)
                {
                    //判断是否手机号未注册【未注册先注册，已注册忽略】
                    IMUtil.ExecuteRequest(1, "accid=" + user.user_phone + "&name=" + user.user_name);
                    IMUtil.ExecuteRequest(1, "accid=" + phone);
                    imresult = IMUtil.ExecuteRequest(8, "from=" + user.user_phone + "&msgtype=0&to=" + phone + $"&attach={attach.ToString()}");
                    json = JsonHelper.JsonStrToObject<IMResult>(imresult);
                }
                if (json.code == 200)
                {
                    //更新推送用户表
                    operateContext.bllSession.T_VRDDSendUser.Modify(new T_VRDDSendUser { push_status = 1, push_date = DateTime.Now }, s => s.id == messUser.id, "push_status", "push_date");
                    //更新推送消息表
                    List<T_VRDDSendUser> userList = operateContext.bllSession.T_VRDDSendUser.Select(s => s.mess_id == mess.mess_id);
                    List<T_VRDDSendUser> pushList = userList.Where(s => s.push_status == 1).ToList();
                    int send_status = 0;
                    if (userList.Count == pushList.Count)
                        send_status = 1;
                    operateContext.bllSession.T_VRDDSendMess.Modify(new T_VRDDSendMess { send_status = send_status }, s => s.mess_id == mess.mess_id, "send_status");
                }else
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, $"网易云信消息推送失败，错误代码：【{json.code}】错误消息：【{json.desc}】", null);
            }
            if (mark > 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "", obj.id);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "申请提交失败！", null);
        }
        #endregion

        #region 1.3 获取合伙人申请列表 + WebApiResultJsonModel GetFounderList(FounderParam param)
        /// <summary>
        ///  1.3 获取合伙人申请列表
        /// </summary>
        /// <param name="param">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel<List<FounderList>> GetFounderList(FounderParam param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel<List<FounderList>>.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            int user_id = HCQ2UI_Helper.Session.SysPermissSession.ChangeIdByGuid(param.userid);
            List<FounderList> list = operateContext.bllSession.T_VRGoldLog.GetFounderList(param, user_id);
            return ApiResultJsonModel<List<FounderList>>.RedirectWebApi(WebResultCode.Ok, "", list);
        }
        #endregion

        #region 1.4 保存合伙人审核结果 + WebApiResultJsonModel SaveApplyFounder(SaveFounderApply param)
        /// <summary>
        ///  保存合伙人审核结果
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel SaveApplyFounder(SaveFounderApply param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            if(param.id<=0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "申请主键id不能为空！", null);
            //审核人信息
            var apply = operateContext.bllSession.T_User.FindSingle(s => s.user_guid.Equals(param.userid));
            if(apply==null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "申请人、或用户id信息异常！", null);
            //判断审核人意见是否允许为空
            if(param.apply_status==2 && string.IsNullOrEmpty(param.approve_note))
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "不通过时必须填写审核意见！", null);
            T_VRFounderApply obj = new T_VRFounderApply
            {
                approve_id = apply.user_id,
                approve_name = apply.user_name,
                approve_note = param.approve_note,
                apply_status = param.apply_status,
                approve_date=DateTime.Now,
                user_level=0
            };
            //申请人
            var t = operateContext.bllSession.T_VRFounderApply.FindSingle(s => s.id == param.id);
            if(t==null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "待审核的记录不存在！", null);
            //【接收人】申请人
            var applyUser = operateContext.bllSession.T_User.FindSingle(o => o.user_id == t.user_id);
            int mark = operateContext.bllSession.T_VRFounderApply.Modify(obj, s => s.id == param.id, "approve_id", "approve_name", "approve_note", "apply_status", "approve_date", "user_level");
            if (mark > 0)
            {
                //获取申请店铺信息
                var folder = operateContext.bllSession.T_DocumentFolder.FindSingle(s => s.folder_id == t.folder_id);
                if(folder==null)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "申请店铺已不存在，不能推送消息！", null);
                if (folder.founder_id <= 0 || string.IsNullOrEmpty(folder.founder_name))
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "申请店铺无创始人，不能推送消息！", null);
                if(string.IsNullOrEmpty(t.apply_phone))
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "申请人无手机号，不能推送消息！", null);
                //发送人【店铺创始人】
                var foundUser = operateContext.bllSession.T_User.FindSingle(o => o.user_id == folder.founder_id);
                string foundPhone = foundUser?.user_phone;
                if (string.IsNullOrEmpty(foundPhone))
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "店铺创始人手机号为空，消息推送失败！", null);
                string mess_type = "101";//通过
                if (param.apply_status==2)
                    mess_type = "102";//未通过
                string mess_note = $"你的合伙申请{(mess_type.Equals("101") ? "已通过" : "未通过")}审核";
                //0、同一个店铺、同一个发送人ID、同一个消息类别、同样的消息内容 只需要创建一条记录
                T_VRDDSendMess mess = operateContext.bllSession.T_VRDDSendMess.FindSingle(s => s.store_id == folder.folder_id && s.send_id == t.user_id && s.mess_type.Equals(mess_type) && s.mess_note.Equals(mess_note));
                //1、添加、更新【推送消息列表】
                if (mess != null)
                {
                    //更新
                    mess.update_id = apply.user_id;
                    mess.update_name = apply.user_name;
                    mess.update_date = DateTime.Now;
                    mess.send_num = mess.send_num + 1;
                    if (mess.send_status == 1)
                        mess.send_status = 0;
                    else
                        mess.send_status = -1;
                    operateContext.bllSession.T_VRDDSendMess.Modify(mess, s => s.mess_id == mess.mess_id, "send_status", "update_id", "update_name", "update_date", "send_num");
                }
                else
                {
                    //添加
                    mess = new T_VRDDSendMess
                    {
                        send_id = foundUser.user_id,
                        send_name = foundUser.user_name,
                        send_status = -1,
                        send_num = 1,
                        mess_type = "100",
                        store_id = folder.folder_id,
                        store_name = folder.folder_name,
                        mess_note = mess_note,
                        create_id = apply.user_id,
                        create_name = apply.user_name,
                        create_date = DateTime.Now,
                        update_id = apply.user_id,
                        update_name = apply.user_name,
                        update_date = DateTime.Now
                    };
                    operateContext.bllSession.T_VRDDSendMess.Add(mess);
                }
                //2、写入推送用户列表
                var messUser = new T_VRDDSendUser
                {
                    mess_id = mess.mess_id,
                    create_id = apply.user_id,
                    create_name = apply.user_name,
                    create_date = DateTime.Now,
                    push_status = -1,
                    store_id = folder.folder_id,
                    store_name = folder.folder_name,
                    accept_id = t.user_id,//接收人【申请人】
                    accept_name = t.apply_name,
                    accept_phone = t.apply_phone,
                    accept_status = -1
                };
                operateContext.bllSession.T_VRDDSendUser.Add(messUser);
                //3、调用网易云信SDK，推送消息到度度圈App
                //店铺logo地址
                StringBuilder attach = new StringBuilder(); // $"{\"logo\":\"{}\"}";
                string logo = !string.IsNullOrEmpty(folder.folder_url) ? folder.folder_url?.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"))) : "";
                attach.Append("{");
                attach.Append("\"logo\":\"" + logo + "\",");//店铺logo地址
                attach.Append("\"userid\":\"" + applyUser.user_guid + "\",");//接收人用户编码
                attach.Append("\"storeName\":\"" + folder.folder_name + "\",");//店铺名
                attach.Append("\"messNote\":\"" + mess.mess_note + "\",");//消息内容
                attach.Append("\"messType\":\"" + mess.mess_type + "\",");//消息类别
                attach.Append("\"storeId\":\"" + mess.store_id + "\",");//店铺ID
                attach.Append("\"messUserId\":\"" + messUser.id + "\"");//推送用户列表主键值
                attach.Append("}");
                string imresult = IMUtil.ExecuteRequest(8, "from=" + foundPhone + "&msgtype=0&to=" + t.apply_phone + $"&attach={attach.ToString()}");
                IMResult json = JsonHelper.JsonStrToObject<IMResult>(imresult);
                if (json.code != 200)
                {
                    //判断是否手机号未注册【未注册先注册，已注册忽略】
                    IMUtil.ExecuteRequest(1, "accid=" + t.apply_phone + "&name=" + t.apply_name);
                    IMUtil.ExecuteRequest(1, "accid=" + foundPhone);
                    imresult = IMUtil.ExecuteRequest(8, "from=" + foundPhone + "&msgtype=0&to=" + t.apply_phone + $"&attach={attach.ToString()}");
                    json = JsonHelper.JsonStrToObject<IMResult>(imresult);
                }
                if (json.code == 200)
                {
                    //更新推送用户表
                    operateContext.bllSession.T_VRDDSendUser.Modify(new T_VRDDSendUser { push_status = 1, push_date = DateTime.Now }, s => s.id == messUser.id, "push_status", "push_date");
                    //更新推送消息表
                    List<T_VRDDSendUser> userList = operateContext.bllSession.T_VRDDSendUser.Select(s => s.mess_id == mess.mess_id);
                    List<T_VRDDSendUser> pushList = userList.Where(s => s.push_status == 1).ToList();
                    int send_status = 0;
                    if (userList.Count == pushList.Count)
                        send_status = 1;
                    operateContext.bllSession.T_VRDDSendMess.Modify(new T_VRDDSendMess { send_status = send_status }, s => s.mess_id == mess.mess_id, "send_status");
                }else
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, $"网易云信消息推送失败，错误代码：【{json.code}】错误消息：【{json.desc}】", null);
            }
            if (mark>0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "", t.user_id);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "保存审核结果异常！", null);
        }
        #endregion

        #region 1.5 是否商家合伙人 + WebApiResultJsonModel CheckFounder(SaleMoneyParam param)
        /// <summary>
        ///  是否商家合伙人
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel CheckFounder(SaleMoneyParam param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            if (param.folder_id <= 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "商铺id异常！", null);
            //审核人信息
            var user = operateContext.bllSession.T_User.FindSingle(s => s.user_guid.Equals(param.userid));
            if (user==null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "用户信息异常！", null);
            var folder = operateContext.bllSession.T_DocumentFolder.FindSingle(s => s.folder_id == param.folder_id);
            if(folder==null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "后台查无此商铺！", null);
            var mark = operateContext.bllSession.T_VRFounderApply.FindSingle(s => s.user_id == user.user_id && s.folder_id == param.folder_id);
            int partner_status = -1;//默认未申请
            if (folder.founder_id == user.user_id)
                partner_status = 100;//用户是创始人
            else if (mark != null)
                partner_status = mark.apply_status;
            Dictionary<string, object> result = new Dictionary<string, object>();
            if (mark!=null)
            {
                result.Add("is_partner", true);
                result.Add("partner_status", partner_status);
                result.Add("user_level", mark.user_level);
            }else
            {
                result.Add("is_partner", false);
                result.Add("partner_status", folder.founder_id == user.user_id ? "100" : "-1");
                result.Add("user_level", 0);
            }
           return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "", result);
        }
        #endregion

        #region 1.6 修改合伙人协议 + WebApiResultJsonModel ModifyAgreement(UserFounderInput param)
        /// <summary>
        /// 修改合伙人协议
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel ModifyAgreement(UserFounderInput param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            T_User user = operateContext.bllSession.T_User.FindSingle(s => s.user_guid.Equals(param.userid));
            if(user==null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "用户信息异常！", null);
            var query = operateContext.bllSession.T_VRFounderDeal.FindSingle(s => s.folder_id == param.folder_id);
            if (query == null)
            {
                //新增
                operateContext.bllSession.T_VRFounderDeal.Add(new T_VRFounderDeal
                {
                    folder_id = param.folder_id,
                    deal_note = param.deal_note,
                    create_id = user.user_id,
                    create_name = user.user_name,
                    create_date = DateTime.Now,
                    update_id = user.user_id,
                    update_name = user.user_name,
                    update_date = DateTime.Now
                });
            }else
            {
                //编辑
                operateContext.bllSession.T_VRFounderDeal.Modify(new T_VRFounderDeal
                {
                    deal_note = param.deal_note,
                    update_id = user.user_id,
                    update_name = user.user_name,
                    update_date = DateTime.Now
                }, s => s.folder_id == param.folder_id, "deal_note", "update_id", "update_name", "update_date");
            }
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "", null);
        }
        #endregion

        #region 1.7 获取合伙人列表 + WebApiResultJsonModel GetFounderList(PartnerInput param)
        /// <summary>
        ///  获取合伙人列表
        /// </summary>
        /// <param name="param">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel<List<PartnerOuput>> GetPartnerList(PartnerInput param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel<List<PartnerOuput>>.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            if (param.mess_status == 0)
                param.mess_status = 2;
            List<PartnerOuput> list = operateContext.bllSession.T_VRFounderApply.GetPartnerList(param);
            return ApiResultJsonModel<List<PartnerOuput>>.RedirectWebApi(WebResultCode.Ok, "", list);
        }
        #endregion

        //****************************************************2.0 用户消息*******************************************************
        #region 2.0 保存用户消息 + WebApiResultJsonModel SaveUserMessage(UserMessageParam param)
        /// <summary>
        ///  保存用户消息
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel<int?> SaveUserMessage(UserMessageParam param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel<int?>.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            if(string.IsNullOrEmpty(param.userid))
                return ApiResultJsonModel<int?>.RedirectWebApi(WebResultCode.Exception, "用户userid必传！", null);
            T_User user = operateContext.bllSession.T_User.FindSingle(s => s.user_guid.Equals(param.userid));
            if (user==null)
                return ApiResultJsonModel<int?>.RedirectWebApi(WebResultCode.Exception, "用户信息有误！", null);
            int mark = operateContext.bllSession.T_VRUserMessage.SelectCount(o => o.user_id == user.user_id && o.folder_id == param.folder_id && o.mess_type == param.mess_type && o.push_from == param.push_from);
            if(mark>0)
                return ApiResultJsonModel<int?>.RedirectWebApi(WebResultCode.Exception,"同一用户、商铺、消息类别、推送平台无需重复保存数据！", null);
            T_User sendUser = operateContext.bllSession.T_User.FindSingle(s => s.user_id == param.send_id);
            if(sendUser==null)
                return ApiResultJsonModel<int?>.RedirectWebApi(WebResultCode.Exception, "发送用户id有误！", null);
            T_VRUserMessage obj = new T_VRUserMessage
            {
                user_id = user.user_id,
                user_name = user.user_name,
                send_id = sendUser.user_id,
                send_name = sendUser.user_name,
                mess_type = param.mess_type,
                mess_content = param.mess_content,
                link_url = param.link_url,
                mess_status = -1,
                push_from = param.push_from,
                create_id = user.user_id,
                create_name = user.user_name,
                create_date = DateTime.Now,
                update_id = user.user_id,
                update_name = user.user_name,
                update_date = DateTime.Now
            };
            mark = operateContext.bllSession.T_VRUserMessage.Add(obj);
            if (mark > 0)
                return ApiResultJsonModel<int?>.RedirectWebApi(WebResultCode.Ok, "", obj.id);
            return ApiResultJsonModel<int?>.RedirectWebApi(WebResultCode.Exception, "保存用户消息失败！", null);
        }
        #endregion

        #region 2.1 更新用户消息 + WebApiResultJsonModel ModifyUserMessage(ModifyUserMessage param)
        /// <summary>
        ///  更新用户消息
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel ModifyUserMessage(ModifyUserMessage param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            int mark = operateContext.bllSession.T_VRUserMessage.SelectCount(s => s.id == param.id);
            if (param.id<=0 || mark<=0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception,"消息id异常！", null);
            var user = operateContext.bllSession.T_User.FindSingle(s => s.user_guid.Equals(param.userid));
            if (user == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "用户id信息有误！", null);
            T_VRUserMessage obj = new T_VRUserMessage
            {
                mess_status = param.mess_status,
                update_id = user.user_id,
                update_name = user.user_name,
                update_date = DateTime.Now
            };
            operateContext.bllSession.T_VRUserMessage.Modify(obj, s => s.id == param.id, "mess_status", "update_id", "update_name", "update_date");
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "用户消息更新成功！", null);
        }
        #endregion

        #region 2.3 获取用户消息 + WebApiResultJsonModel GetUserMessage(UserMessPram param)
        /// <summary>
        ///  获取用户消息
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel<List<UserMessageModel>> GetUserMessage(UserMessPram param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel<List<UserMessageModel>>.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            int user_id = HCQ2UI_Helper.Session.SysPermissSession.ChangeIdByGuid(param.userid);
            List<UserMessageModel> list = operateContext.bllSession.T_VRUserMessage.GetUserMessage(param);
            return ApiResultJsonModel<List<UserMessageModel>>.RedirectWebApi(WebResultCode.Ok, "", list);
        }
        #endregion

        //****************************************************0322 需求*******************************************************
        #region 3.0 获取下线用户 + WebApiResultJsonModel GetOffLineUser(OffLineUserParam param)
        /// <summary>
        ///  获取下线用户
        /// </summary>
        /// <param name="param">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel<List<PartnerOuput>> GetOffLineUser(OffLineUserParam param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel<List<PartnerOuput>>.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            if (param.mess_status == 0)
                param.mess_status = 2;
            List<PartnerOuput> list = operateContext.bllSession.T_VRFounderApply.GetOffLineUserList(param);
            return ApiResultJsonModel<List<PartnerOuput>>.RedirectWebApi(WebResultCode.Ok, "", list);
        }
        #endregion

        #region 3.1 获取积分明细 + WebApiResultJsonModel GetScoreDetail(OffLineUserParam param)
        /// <summary>
        ///  获取积分明细
        /// </summary>
        /// <param name="param">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel<List<ScoreDetialResult>> GetScoreDetail(OffLineUserParam param)
        {
            if (!ModelState.IsValid) 
                return ApiResultJsonModel<List<ScoreDetialResult>>.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            List<ScoreDetialResult> list = operateContext.bllSession.T_VRFounderApply.GetScoreDetial(param);
            return ApiResultJsonModel<List<ScoreDetialResult>>.RedirectWebApi(WebResultCode.Ok, "", list);
        }
        #endregion

        //****************************************************2021-06-07 需求*******************************************************
        #region 4.0 ✔ 获取商铺合伙人申请的统计 + WebApiResultJsonModel GetPartnerNum(InputPartnerNum param)
        /// <summary>
        ///  4.0 ✔ 获取商铺合伙人申请的统计
        /// </summary>
        /// <param name="param">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel<OutputPartnerNum> GetPartnerNum(InputPartnerNum param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel<OutputPartnerNum>.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            //判断商铺是否存在
            var obj = operateContext.bllSession.T_DocumentFolder.FindSingle(s => s.folder_id == param.folder_id);
            if(obj==null)
                return ApiResultJsonModel<OutputPartnerNum>.RedirectWebApi(WebResultCode.Exception,"指定商铺id不存在！", null);
            OutputPartnerNum result = new OutputPartnerNum { folder_id = param.folder_id, folder_name = obj.folder_name };
            var list = operateContext.bllSession.T_VRFounderApply.Select(s => s.folder_id == param.folder_id);
            result.apply_num = list.Count;
            result.approve_num = list.Where(s => s.apply_status == 0).Count();
            result.finish_num = list.Where(s => s.apply_status == 1).Count();
            result.notPass_num = list.Where(s => s.apply_status == 2).Count();
            return ApiResultJsonModel<OutputPartnerNum>.RedirectWebApi(WebResultCode.Ok, "", result);
        }
        #endregion

        #region 4.1 ✔ 作品/素材下架 + WebApiResultJsonModel VRSoldOut(DownFileParam param)
        /// <summary>
        ///  4.1 ✔ 作品/素材下架
        /// </summary>
        /// <param name="param">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel VRSoldOut(DownFileParam param)
        {
            if (param.file_id<=0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "作品/素材id必传项！", null);
            //判断商品是否存在
            int mark = operateContext.bllSession.T_DocumentInfo.SelectCount(s => s.file_id == param.file_id);
            if (mark<=0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "指定商品不存在！", null);
            mark = operateContext.bllSession.T_DocumentInfo.Modify(new T_DocumentInfo { file_status = 4 }, s => s.file_id == param.file_id, "file_status");
            if(mark>0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "商品下架成功！", null);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "商品下架失败！", null);
        }
        #endregion

        #region 4.2  ✔修改商铺推荐【商品表的商铺推荐字段】 + WebApiResultJsonModel ModifySoreStatus(InputStoreTop param)
        /// <summary>
        ///  4.2 ✔ 修改商铺推荐
        /// </summary>
        /// <param name="param">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel ModifySoreStatus(InputStoreTop param)
        {
            if (param.file_id <= 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "商品id必传项！", null);
            //判断商品是否存在
            int mark = operateContext.bllSession.T_DocumentInfo.SelectCount(s => s.file_id == param.file_id);
            if (mark <= 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "指定商品不存在！", null);
            mark = operateContext.bllSession.T_DocumentInfo.Modify(new T_DocumentInfo { store_top = param.store_top }, s => s.file_id == param.file_id, "store_top");
            if (mark > 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "商铺推荐修改成功！", null);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "商铺推荐修改失败！", null);
        }
        #endregion

        #region 4.3 ✔ 批量修改商品序号 + WebApiResultJsonModel BatchModifyNumber(InputModifyOrder param)
        /// <summary>
        ///  4.3 ✔ 批量修改商品序号
        /// </summary>
        /// <param name="param">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel BatchModifyNumber(InputModifyOrder param)
        {
            if (param.goods ==null && param.goods.Count<=0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "请指定需要修改的商品！", null);
            param.goods?.ForEach(s => operateContext.bllSession.T_DocumentInfo.Modify(new T_DocumentInfo { file_order = s.number }, o => o.file_id == s.file_id, "file_order"));
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "商品序号修改成功！", null);
        }
        #endregion
    }
}